package cn.test.yuecai.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HandleResponseData {

	//从文件中读取内容并转化为string类型
	public static String getTdDataFromFile(String pathname) throws Exception {
		String resData = null;
		// 从文件中读取内容，并存放在sBuffer内 
		File file = new File(pathname);
		if (!(file.exists() || file.isDirectory())) {
			throw new FileNotFoundException("file is not exist");
		}
		FileInputStream fis = new FileInputStream(file);
		byte[] buffer = new byte[1024];
		StringBuffer sBuffer = new StringBuffer();
		while (fis.read(buffer) != -1) {
			sBuffer.append(new String(buffer));
			buffer = new byte[1024];
		}
		fis.close();
		// 处理sBuffer
		resData = sBuffer.toString();
		return resData;
	}

	//从字符串中按一定的分隔符，形成字符数组
	public static String[] getTdData(String resData,String fixStr) {
		String[] trData = null;
		trData = resData.split(fixStr);
		return trData;
	}
	
	//从字符数组中，找出UserId和LoginName
	public static Map<String, String> fetchUserIdAndName(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		for (String str : args) {
			int index1 = str.indexOf("cgs0119a");
			if (index1 ==-1) {
				continue;
			}
			int index2 = index1 + 11;
			String loginName = str.substring(index1, index2);
			int index3 = str.indexOf("value=\"");
			int index4 = str.substring(index3 + 7).indexOf("\"/>");
			String value = str.substring(index3 + 7).substring(0, index4);
			map.put(loginName, value);
		}
		return map;
	}
	public static void main(String[] args) {
		String[] trData = null;
		String pathName = "G:\\test.txt";
		String fixStr = "<tr id=\"userlist\">";
		try {
			trData = getTdData(getTdDataFromFile(pathName),fixStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, String> map = fetchUserIdAndName(trData);
		Set<String> keySet = map.keySet();
		for (String key : keySet) {
			System.out.println(key + "," + map.get(key));
		}
	}

}
